package sample;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import javafx.event.ActionEvent;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

public class Controller {

    public Label note;
    public TextArea cookie;
    public TextField startDate;
    public TextField endDate;

    public void start(ActionEvent actionEvent) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            Date now = new Date();
            String cookieText = cookie.getText();
            if (isEmpty(cookieText)) {
                throw new RuntimeException("cookie不能为空");
            }
            String startDateText = startDate.getText();
            if (isEmpty(startDateText)) {
                startDateText = sdf.format(now);
            }
            String endDateText = endDate.getText();
            if (isEmpty(endDateText)) {
                endDateText = sdf.format(now);
            }
            Date sd = null;
            Date ed = null;
            try {
                sd = sdf.parse(startDateText);
                ed = sdf.parse(endDateText);
            } catch (Exception e) {
                throw new RuntimeException("日期格式错误");
            }
            note.setText("执行中");
//            String s = outExcel(sd, ed, cookieText.trim());
            note.setText("文件（" + 123 + "）创建成功");
        } catch (Exception e) {
            note.setText(e.toString());
        }


    }

    public boolean isEmpty(String str) {
        return str == null || "".equals(str);
    }


    public String readFile(String path) {
        BufferedReader reader = null;
        StringBuilder lastStr = new StringBuilder();
        try {
            FileInputStream fileInputStream = new FileInputStream(path);
            InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
            reader = new BufferedReader(inputStreamReader);
            String tempString = null;
            while ((tempString = reader.readLine()) != null) {
                lastStr.append(tempString);
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return lastStr.toString();
    }


//    public void main(String[] args) {
////        HttpClient client = new HttpClient();
//        String url = "https://app-api.shop.ele.me/nevermore/invoke/?method=OrderService.queryOrder";
//        try {
//            CloseableHttpClient httpClient = HttpClients.createDefault();
//            HttpPost httpPost = new HttpPost(url);
//            JSONObject jsonObject = new JSONObject();
//            jsonObject.put("key", "hjkhkdsa");
//            try {
//                StringEntity stringEntity = new StringEntity("{\"id\":\"FDA613647F274137BA3DEA669D0CCC07|1611240487341\",\"metas\":{\"appName\":\"melody\",\"appVersion\":\"5.0.4\",\"ksid\":\"NMY5YMMTA1MjcxMTAyOTk1OTAxTlUvdm04VTBQ\",\"key\":\"1.0.0\"},\"service\":\"OrderService\",\"method\":\"queryOrder\",\"params\":{\"shopId\":501387112,\"orderFilter\":\"ORDER_QUERY_ALL\",\"condition\":{\"beginTime\":\"2021-01-20T00:00:00\",\"endTime\":\"2021-01-20T23:59:59\",\"offset\":0,\"limit\":20,\"bookingOrderType\":null}},\"ncp\":\"2.0.0\"}", "application/json", "utf-8");
//                httpPost.setEntity(stringEntity);
//                CloseableHttpResponse closeableHttpResponse = httpClient.execute(httpPost);
//                HttpEntity httpEntity = closeableHttpResponse.getEntity();
//                String res = EntityUtils.toString(httpEntity);//响应内容
//                System.out.println(res);
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }

    public JSONArray getOrderJxJson() {
        return JSONObject.parseArray(readFile(getResource("orderjx.json")));
    }

    public JSONArray getItemJxJson() {
        return JSONObject.parseArray(readFile(getResource("caipinjx.json")));
    }


    public HSSFSheet addTitle(HSSFWorkbook book, List<String> titles, String sheetName) {
        HSSFSheet sheet = book.createSheet(sheetName);
        HSSFRow row = sheet.createRow(0);
        for (int i = 0; i < titles.size(); i++) {
            HSSFCell cell = row.createCell(i);
            cell.setCellValue(titles.get(i));
        }
        return sheet;
    }

    public void addData(HSSFSheet sheet, JSONArray array, int startNum, List<String> keys) {
        for (int i = 0; i < array.size(); i++) {
            JSONObject obj = array.getJSONObject(i);
            HSSFRow row = sheet.createRow(startNum);
            startNum++;
            for (int j = 0; j < keys.size(); j++) {
                HSSFCell cell = row.createCell(j);
                cell.setCellValue(obj.getString(keys.get(j)));
            }
        }
    }

    public String outFile(HSSFWorkbook book, String name) throws Exception {
        String fileName = name + ".xlsx";
        File file = new File(fileName);
        if (file.exists()) {
            return outFile(book, name + "1");
        } else {
            OutputStream out = new FileOutputStream(fileName);
            book.write(out);
            out.close();
            return fileName;
        }

    }

    public String getResource(String str) {
        return getClass().getResource(str).getPath();
    }

    public Properties getProperty(String str) {
        Properties properties = new Properties();
        try {
            BufferedReader bufferedReader = new BufferedReader(new FileReader(getResource(str)));
            properties.load(bufferedReader);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return properties;
    }


    public String getMtUrl() {
        return getProperty("url.properties").getProperty("mt.list.url");
    }

    public String outExcel(Date sd, Date ed, String cookie) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        Date tmp = null;
        if (sd.getTime() > ed.getTime()) {
            tmp = sd;
            sd = ed;
            ed = tmp;
        }
        HSSFWorkbook book = new HSSFWorkbook();
        JSONArray orderList = new JSONArray();
        JSONArray itemList = new JSONArray();
        getResponse(sd, ed, cookie, null, orderList, itemList);
        JSONArray orderArray = getOrderJxJson();
        createSheet(book, orderList, sdf.format(sd) + "-" + sdf.format(ed) + "订单", orderArray);
        JSONArray itemArray = getItemJxJson();
        createSheet(book, itemList, sdf.format(sd) + "-" + sdf.format(ed) + "菜品", itemArray);
        return outFile(book, sdf.format(sd) + "-" + sdf.format(ed) + "订单详情");
    }

    private void createSheet(HSSFWorkbook book, JSONArray data, String sheetName, JSONArray jxArray) {
        List<String> titles = new ArrayList<>();
        List<String> keys = new ArrayList<>();
        for (int i = 0; i < jxArray.size(); i++) {
            JSONObject jsonObject = jxArray.getJSONObject(i);
            titles.add(jsonObject.getString("title"));
            keys.add(jsonObject.getString("key"));
        }
        HSSFSheet sheet = addTitle(book, titles, sheetName);
        addData(sheet, data, 1, keys);
    }

    public void getResponse(Date sd, Date ed, String cookie, JSONObject next, JSONArray orderList, JSONArray itemList) throws Exception {
        String url = getMtUrl();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String nextUrl = "";
        if (next != null) {
            nextUrl = URLEncoder.encode(next.toJSONString(), "UTF-8");
        }
        url = url.replace("@st@", sdf.format(sd)).replace("@sd@", sdf.format(ed)).replace("@next@", nextUrl);
        HttpClient hc = new HttpClient();
        GetMethod gm = new GetMethod(url);
        gm.setRequestHeader("cookie", cookie);
        int code = hc.executeMethod(gm);
        int success = 200;
        if (code != success) {
            throw new RuntimeException(gm.getResponseBodyAsString());
        }
        String rs = gm.getResponseBodyAsString();
        JSONObject object = JSON.parseObject(rs);
        JSONObject data = object.getJSONObject("data");
        JSONObject nextLabel = data.getJSONObject("nextLabel");
        JSONArray wmOrderList = data.getJSONArray("wmOrderList");
        int orderNum = orderList.size();

        if (wmOrderList != null) {
            for (int i = 0; i < wmOrderList.size(); i++) {
                JSONObject jo = wmOrderList.getJSONObject(i);
                jo.put("no", orderNum + i + 1);
                String otf = jo.getString("order_time_fmt");
                String sub = otf.substring(0, otf.indexOf(" "));
                jo.put("order_date", sub);
                String orderNo = jo.getString("wm_order_id_view");
                JSONArray details = jo.getJSONArray("cartDetailVos").getJSONObject(0).getJSONArray("details");
                orderList.add(jo);
                int itemNum = itemList.size();
                for (int j = 0; j < details.size(); j++) {
                    JSONObject detail = details.getJSONObject(j);
                    detail.put("no", itemNum + j + 1);
                    detail.put("order_no", orderNo);
                    detail.put("order_date", sub);
                    detail.put("poi_name", jo.getString("poi_name"));
                    itemList.add(detail);
                }
            }

        }

        if (nextLabel != null) {
            getResponse(sd, ed, cookie, nextLabel, orderList, itemList);
        }
    }
}
